import random

import json
import time
import threading
from sys import stdout, stdin

PUBLISH_NAME = "websocket"

is_quit = 0  # 线程退出标识
device_id = ""  # 设备唯一id
out_time = 60  # 超时时间


def receive():
    """
            接收数据
    """
    global device_id
    global is_quit
    global out_time
    while 1:
        str_receive = stdin.readline().strip()
        if not str_receive:
            is_quit = 1
            break
        # 处理心跳数据
        if str_receive == "ping":
            out_time = 60
            send("pong")
            continue
        # 处理数据，数据格式str(json)
        t_json = None
        try:
            t_json = json.loads(str_receive)
        except:
            t_json = {}
        device_id = t_json.get("device_id", "")
        if device_id == "":
            is_quit = 1
            break

def toDo(message="{}"):
    if message != "":
        s = message.decode()
        send(s)

def send(str_send):
    """
            发送数据
    str_send: str
    """
    str_send = str_send + "\n"
    stdout.write(str_send)
    stdout.flush()

if __name__ == '__main__':
    
    # 收消息线程
    t0 = threading.Thread(target=receive)
    t0.setDaemon(True)
    t0.start()    

    # 主程序循环，接收超时或者主动退出
    while is_quit == 0:
        time.sleep(1)
        out_time -= 1
        if out_time <= 0:
            break
